<template>
	<view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				loading: false,
				goodsindex: 0,
				msgType: 'success',
				datas: {
					user_id: '',
					goods: [],
					directUpload: 1,
					type: 2
				},
				dataarr: [],
				page: 1,
				pagesize: 30,
				isModalOpen: false
			};
		},
		computed: {
			...mapState(['data'])
		},
		onLoad() {
			this.createWebviewAndLoadURL();
		},
		methods: {

			createWebviewAndLoadURL() {
				// 在 APP-PLUS 平台下执行以下代码
				// #ifdef APP-PLUS
				let loadCount = 0;
				const wv = plus.webview.create("", "custom-webview", {
					plusrequire: "none",
					'uni-app': 'none',
					top: uni.getSystemInfoSync().statusBarHeight + 44,
					bottom: 0
				});

				this.handleWebViewLoaded(wv)


				wv.loadURL(
					"https://havanalogin.taobao.com/mini_login.htm?lang=zh_CN&appName=wap1688&appEntrance=h5&isMobile=true&showWelcomePage=false&hideItem=false&returnUrl=https://m.1688.com/pass.html"
				);
				setTimeout(function() {
					wv.loadURL(
						"https://havanalogin.taobao.com/mini_login.htm?lang=zh_CN&appName=wap1688&appEntrance=h5&isMobile=true&showWelcomePage=false&hideItem=false&returnUrl=https://m.1688.com/pass.html"
					);
				}, 100);
				const currentWebview = this.$scope.$getAppWebview();
				currentWebview.append(wv);

				// 延时一秒后获取 Webview 样式
				setTimeout(function() {
					console.log(wv.getStyle());
				}, 1000);

				function unescapeString(str) {
					return str.replace(/\\n/g, '\n')
						.replace(/\\r/g, '\r')
						.replace(/\\t/g, '\t')
						.replace(/\\b/g, '\b')
						.replace(/\\f/g, '\f')
						.replace(/\\"/g, '"')
						.replace(/\\\\/g, '\\');
				}


				// #endif

			},
			
			createWebviewAndLoadURL2(url) {
				// 在 APP-PLUS 平台下执行以下代码
				// #ifdef APP-PLUS
				let loadCount = 0;
				const wv = plus.webview.create("", "custom-webview", {
					plusrequire: "none",
					'uni-app': 'none',
					top: uni.getSystemInfoSync().statusBarHeight + 44
				});
			
				this.handleWebViewLoaded(wv)
			
			
			
				// wv.loadURL(url);
				setTimeout(function() {
					wv.loadURL(url);
				}, 100);
				const currentWebview = this.$scope.$getAppWebview();
				currentWebview.append(wv);
			
				// 延时一秒后获取 Webview 样式
				setTimeout(function() {
					console.log(wv.getStyle());
				}, 1000);
			
				function unescapeString(str) {
					return str.replace(/\\n/g, '\n')
						.replace(/\\r/g, '\r')
						.replace(/\\t/g, '\t')
						.replace(/\\b/g, '\b')
						.replace(/\\f/g, '\f')
						.replace(/\\"/g, '"')
						.replace(/\\\\/g, '\\');
				}
			
			
				// #endif
			
			},

			decodeString(str) {
				var result = '';
				for (var i = 0; i < str.length; i++) {
					if (str[i] === 'u' && i + 4 < str.length) {
						var hexCode = str.substr(i + 1, 4);
						result += String.fromCharCode(parseInt(hexCode, 16));
						i += 4;
					} else {
						result += str[i];
					}
				}
				return result;
			},

			strdemctrion(rules1, rules2, stritem) {
				var pattern = new RegExp(rules1 + "(.*?)" + rules2, "g");
				var match = stritem.match(pattern);
				if (match) {
					return match; // 返回匹配到的内容
				} else {
					return "未找到匹配的结果";
				}
			},

			strdemctrion2(rules1, rules2, stritems) {
				let arritem = []
				if (stritems != '未找到匹配的结果' && stritems.length > 0) {
					stritems.forEach(stritem => {
						var pattern = new RegExp(rules1 + "(.*?)" + rules2);
						var match = stritem.match(pattern);
						if (match) {
							arritem.push(match[1])
						} else {
							arritem.push('')
						}
					});
					return arritem
				} else {
					return arritem
				}


			},

			strdemctrion3(rules1, rules2, stritem) {
				var pattern = new RegExp(rules1 + "(.*?)" + rules2);
				var match = stritem.match(pattern);
				if (match) {
					return match[1]; // 返回匹配到的内容
				} else {
					return "未找到匹配的结果";
				}
			},

			handleWebViewLoaded(wv) {
				wv.addEventListener("loaded", () => {
					wv.overrideUrlLoading({
						mode: 'reject'
					}, (e) => {
						console.log('拦截请求：' + e.url);

						if (e.url.includes("m.1688.com/pass.html")) {
							this.dataarr = []
							this.page = 1
							this.datas.goods = []
							let url =
								`https://trade.1688.com/order/buyer_order_list.htm?trade_status=waitbuyerreceive&page=${this.page}&page_size=${this.pagesize}`
							wv.loadURL(
								url
							);
						} else if (e.url.includes("trade.1688.com/order/buyer_order_list.htm")) {
							uni.showLoading({
								title: '加载中，耐心等待...'
							});
							uni.request({
								url: e.url,
								method: e.method,
								success: res => {
									
									this.goodsindex = 0
									const htmlString = JSON.stringify(res.data)
									let lihtmls = []
									// console.log(htmlString)
									// 使用正则表达式匹配并提取满足条件的子串
									var pattern = /<li class=\\\"item-active(.*?)<\/li>/g;
									var matches = htmlString.match(pattern);
									// // 输出匹配到的结果
									// console.log(JSON.stringify(matches))
									if (matches) {
										for (var i = 0; i < matches.length; i++) {
											let item = matches[i]
											let stritem = item.replace(/\\/g, '');
											let order_sn = this.strdemctrion(
												'<span class=\\\"order-id\\\">', '</span>',
												stritem);
											// console.log(order_sn)
											let good_name = this.strdemctrion(
												"<a class=\'productName\'", '<\/a>',
												stritem);
											let good_price = this.strdemctrion(
												"<div data-unit-price", '>', stritem)
											let gooddetailurl = this.strdemctrion(
												'<a class=\"bannerOrderDetail\"', '<\/a>',
												stritem)
											let unit_price = this.strdemctrion(
												'<div class=\"total\"', '<\/div>', stritem)
											let good_img = this.strdemctrion("<img", '\/>',
												stritem)
											let good_Items = this.strdemctrion(
												'trade-spec', '<\/div>',
												stritem)
											let num = this.strdemctrion('<td class=\"s4\">',
												' <\/td>', stritem)


											let a = {
												order_sn: this.strdemctrion2('订单号：',
													' <\/',
													order_sn),
												good_name: this.strdemctrion2(
													"target=\'_blank\'>", '<\/a>',
													good_name),
												good_price: this.strdemctrion2('title=\"',
													'\">', good_price),
												gooddetailurl: this.strdemctrion2(
													'href=\"',
													'\"', gooddetailurl),
												unit_price: this.strdemctrion2('title=\"',
													'\"',
													unit_price),
												good_img: this.strdemctrion2('src=\'',
													'\'',
													good_img),
												good_Items: this.strdemctrion2(
													'sku-item\">',
													'<font', good_Items),
												good_Items2: this.strdemctrion2('<span>',
													'<\/span', good_Items),
												num: this.strdemctrion2('title=\"', '\"',
													num)
											}
											this.dataarr.push(a)
										}
										// this.dataarr = lihtmls
										
										
										// let url =
										// 	`https://trade.1688.com/order/new_step_order_detail.htm?orderId=${this.dataarr[this.goodsindex].order_sn[0]}&isHis=y`
										
										this.page += 1
										let url = `https://trade.1688.com/order/buyer_order_list.htm?trade_status=waitbuyerreceive&page=${this.page}&page_size=${this.pagesize}`
										wv.loadURL(url);


									} else {
										if (this.page == 1) {
											console.log('未找到匹配的结果');
											uni.hideLoading();
											uni.setStorageSync('albbparamsdata', JSON
												.stringify(this.datas));
											uni.navigateTo({
												url: '/pages/albbimport/albbgoods'
											});
										} else {
											let url =
												`https://trade.1688.com/order/new_step_order_detail.htm?orderId=${this.dataarr[this.goodsindex].order_sn[0]}&isHis=y`
											wv.loadURL(url);
										}
										
									}



								},
								fail: err => {
									console.error('请求失败：', err);
									this.loading = false
								}
							});
						} else if (e.url.includes("trade.1688.com/order/new_step_order_detail.htm")) {
							uni.request({
								url: e.url,
								method: e.method,
								success: res => {
									
									uni.showLoading({
										title: `获取订单信息中 ${this.goodsindex + 1}/${this.dataarr.length}`
									});
									let rawData = JSON.stringify(res.data)
									// console.log(rawData)
									let articlestr = this.strdemctrion3('<!--物流-->',
										'<\/article>', rawData)
									// console.log(articlestr) 
									let logisticscompany = this.strdemctrion3(
										'data-logistics-company-name', '>', articlestr)
									let logisticscompany2 = this.strdemctrion3('\\"', '\\\\"',
										logisticscompany)
									let logistics_sn = this.strdemctrion3('data-bill-no', '>',
										articlestr)
									let logistics_sn2 = this.strdemctrion3('\\"', '\\\\"',
										logistics_sn)
										// console.log(logisticscompany2)
									this.dataarr[this.goodsindex].logisticscompany =
										logisticscompany2 != '未找到匹配的结果' ? logisticscompany2 :
										''
										// console.log(logistics_sn2)
									this.dataarr[this.goodsindex].logistics_sn =
										logistics_sn2 != '未找到匹配的结果' ? logistics_sn2 : ''
									if (this.goodsindex + 1 < this.dataarr.length) {
										this.goodsindex += 1
										let url =
											`https://trade.1688.com/order/new_step_order_detail.htm?orderId=${this.dataarr[this.goodsindex].order_sn[0]}&isHis=y`
										wv.loadURL(url);
									} else {
										// console.log(JSON.stringify(this.dataarr))
										this.datas.user_id = this.data.user.user_id
										for (var i = 0; i < this.dataarr.length; i++) {
											let item = this.dataarr[i]
											for (var j = 0; j < item.good_name.length; j++) {
												let picimg = item.good_img[j]
													.replace('80x80', '300x300');
												let a = {
													order_sn: item.order_sn[0],
													good_name: item.good_name[j],
													good_price: item.good_price[j],
													unit_price: item.unit_price[0],
													good_img: 'https:' + picimg,
													good_Items: item.good_Items[j] == undefined ? '' : item.good_Items[j] + '：' + item.good_Items2[j],
													num: item.good_name[j],
													logisticscompany: item
														.logisticscompany,
													logistics_sn: item.logistics_sn,
													checked: false
												}
												this.datas.goods.push(a)
												// console.log(JSON.stringify(this.datas.goods))
												if (i + 1 == this.dataarr.length && j + 1 ==
													item.good_name.length) {
													// console.log(JSON.stringify(this.datas.goods))
													uni.hideLoading();
													uni.setStorageSync('albbparamsdata', JSON
														.stringify(this.datas));
													// console.log('111111')
													uni.navigateTo({
														url: '/pages/albbimport/albbgoods'
													});
												}
											}
										}
										// uni.hideLoading();
										// uni.setStorageSync('taobaoparamsdata', JSON.stringify(this.datas) );
										// // console.log('111111')
										// uni.navigateTo({
										// 	url: '/pages/taobaoimport/taobaogoods'
										// });
									}
								},
								fail: err => {
									console.error('请求失败：', err);
								}
							});
						} else {
							console.log('拦截')
							if (!this.isModalOpen) {
								this.openModal() 
							}
							
							
							setTimeout(() => {
								console.log('重新加载')
								this.createWebviewAndLoadURL2(e.url)
							}, 2000);
							uni.off('loaded', wv);
						}


					});

				})
			},
			openModal() {
				uni.showModal({
					title: '即将进入1688验证...（请耐心等待）',
					content: '注意：如提示验证失败，请返回首页重新登录。',
					success: function(res) {
						if (res.confirm) {
							// console.log('用户点击确定');
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
						// 关闭模态框时设置状态为false
						this.isModalOpen = false;
					}
				});
				// 打开模态框时设置状态为true
				this.isModalOpen = true;
			},




		},
		mounted: () => {

		}
	}
</script>

<style>

</style>